// 路由导航守卫，做权限管理：
import router from '@/router'
import store from './store'
import getPageTitle from '@/utils/get-page-title'
import NProgress from 'nprogress' // 导入 NProgress
import 'nprogress/nprogress.css' // 导入 NProgress 的样式
import { asyncRoutes } from '@/router'
// NProgress.start()  ======> 开启进度条
// NProgress.done()     ======> 关闭进度条
const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  console.log(to.path, '去哪里')
  console.log(from.path, '从哪里来')
  NProgress.start()
  const token = store.state.user.token
  // 有token:
  if (token) {
    if (to.path === '/login') {
      console.log('已经登录了，不能再登录了，跳转首页')
      next('/')
      // 手动关闭
      NProgress.done()
    } else {
      console.log('已登录,去其他页面，放行')
      // 判断有没有用户信息,如果有直接跳转，没有就发送请求
      if (!store.state.user.userInfo.userId) {
        const menus = await store.dispatch('user/setUserInfo')
        console.log(menus, 'menus')
        console.log(asyncRoutes, 'asyncRoutes')
        const filterRoutes = asyncRoutes.filter(item => {
          return menus.includes(item.children[0].name)
        })
        console.log(filterRoutes, 'filterRoutes')
        filterRoutes.push({ path: '*', redirect: '/404', hidden: true })
        router.addRoutes(filterRoutes)
        store.commit('menus/setMenusList', filterRoutes)
        next({ ...to, replace: true })
      } else {
        next()
      }
    }
    // 没有登录,没有token
  } else {
    // 在白名单上,放行
    if (whiteList.includes(to.path)) {
      console.log('在白名单上，放行')
      next()
    } else {
      console.log('没有登录,没有token,跳转登录页')
      next('/login')
      // 手动关闭
      NProgress.done()
    }
  }
})
router.afterEach(() => {
  NProgress.done()
})
